package client

import (
	"errors"
	"github.com/aberic/gnomon"
	proto "gykjgit.dccnet.com.cn/chain/proto/swarm"
	"strconv"
	"strings"
	"time"
)

func containerState(state string) proto.ContainerState {
	switch state {
	default:
		return proto.ContainerState_shutdown
	case "Running":
		return proto.ContainerState_running
	case "Shutdown":
		return proto.ContainerState_shutdown
	case "accepted":
		return proto.ContainerState_accepted
	}
}

func serviceMode(mode string) proto.Mode {
	switch mode {
	default:
		return proto.Mode_global
	case "replicated":
		return proto.Mode_replicated
	}
}

func currentStateLastTime(state string) (time.Time, error) {
	stateArr := strings.Split(state, " ")
	var intState = -1
	for _, s := range stateArr {
		if s == "Running" || s == "Failed" {
			continue
		}
		if intState <= 0 {
			if s == "about" {
				continue
			}
			if s == "a" {
				intState = 1
				continue
			}
			var err error
			intState, err = strconv.Atoi(s)
			if nil != err {
				return time.Now(), err
			}
			if intState < 0 {
				return time.Now(), errors.New("stack info read error")
			}
		} else {
			return formatLastTime(intState, s)
		}
	}
	return time.Now(), errors.New("stack info read error")
}

func formatLastTime(intState int, state string) (time.Time, error) {
	switch state {
	case "second":
		return time.Now(), nil
	case "seconds":
		return time.Now().Add(time.Duration(0-intState) * time.Second), nil
	case "minute":
		return time.Now().Add(time.Duration(-1) * time.Minute), nil
	case "minutes":
		return time.Now().Add(time.Duration(0-intState) * time.Minute), nil
	case "hour":
		return time.Now().Add(time.Duration(-1) * time.Hour), nil
	case "hours":
		return time.Now().Add(time.Duration(0-intState) * time.Hour), nil
	case "day":
		return time.Now().Add(time.Duration(-24) * time.Hour), nil
	case "days":
		return time.Now().Add(time.Duration(0-intState*24) * time.Hour), nil
	case "week":
		return time.Now().Add(time.Duration(-168) * time.Hour), nil
	case "weeks":
		return time.Now().Add(time.Duration(0-intState*168) * time.Hour), nil
	case "month":
		return time.Now().Add(time.Duration(-720) * time.Hour), nil
	case "months":
		return time.Now().Add(time.Duration(0-intState*720) * time.Hour), nil
	case "year":
		return time.Now().Add(time.Duration(-8760) * time.Hour), nil
	case "years":
		return time.Now().Add(time.Duration(0-intState*8760) * time.Hour), nil
	}
	return time.Now(), errors.New("stack info read error")
}

// port eg: *:8000->8000/tcp, *:9000->9000/tcp
func formatPort(port string) []*proto.PortMapping {
	var ports []*proto.PortMapping
	portSplit := strings.Split(gnomon.StringTrim(port), ",")
	for _, pBefore := range portSplit {
		if gnomon.StringIsEmpty(pBefore) {
			continue
		}
		pArr := strings.Split(pBefore, "/")
		pArr1 := strings.Split(strings.Split(pArr[0], ":")[1], "->")
		ports = append(ports, &proto.PortMapping{
			Protocol:      pArr[1],
			ContainerPort: pArr1[0],
			OutputPort:    pArr1[1],
		})
	}
	return ports
}
